package com.project.dhCamera.service.impl;

import com.project.dhCamera.entity.CommandTasker;
import com.project.dhCamera.handler.TaskHandler;
import com.project.dhCamera.service.CommandAssembly;
import com.project.dhCamera.service.FFmpegManager;
import com.project.dhCamera.service.TaskDao;
import com.project.dhCamera.utils.ProgramConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Sweey Zhang
 * @description
 * @date 2021/7/20 11:21
 */
@Component
public class FFmpegManagerImpl implements FFmpegManager {
    @Value("${ff.path}")
    private String path;//默认命令行执行根路径
    @Autowired
    private ProgramConfig config;
    /**
     * 任务持久化器
     */
    @Autowired
    private TaskDao taskDao;
    /**
     * 任务执行处理器
     */
    @Autowired
    private TaskHandler taskHandler;
    /**
     * 命令组装器
     */
    @Autowired
    private CommandAssembly commandAssembly;


    /**
     * @param assembly
     * @return
     * @Description //TODO
     * @author Sweey Zhang
     * @Date 2021/7/20 11:53
     */
    @Override
    public String start(Map<String, String> assembly) {
        // ffmpeg环境是否配置正确
        if (checkConfig()) {
            System.err.println("配置未正确加载，无法执行");
            return null;
        }
        // 参数是否符合要求
        if (assembly == null || assembly.isEmpty() || !assembly.containsKey("appName")) {
            System.err.println("参数不正确，无法执行");
            return null;
        }
        String appName = (String) assembly.get("appName");
        if (appName != null && "".equals(appName.trim())) {
            System.err.println("appName不能为空");
            return null;
        }
        assembly.put("ffmpegPath", config.getPath() + "ffmpeg");
        String command = null;
        if (commandAssembly != null) {
            command = commandAssembly.assembly(assembly);
        }
        if (command != null) {
            return start(appName, command, true);
        }

        return null;
    }

    @Override
    public String start(String id, String command, boolean hasPath) {
        if (id != null && command != null) {
            CommandTasker tasker = taskHandler.process(id, hasPath ? command : config.getPath() + command);
            if (tasker != null) {
                int ret = taskDao.add(tasker);
                if (ret > 0) {
                    return tasker.getId();
                } else {
                    // 持久化信息失败，停止处理
                    taskHandler.stop(tasker.getProcess(), tasker.getThread());
                    if (config.isDebug()) {
                        System.err.println("持久化失败，停止任务！");
                    }
                }
            }
        }
        return null;
    }

    @Override
    public boolean stop(String id) {
        if (id != null && taskDao.isHave(id)) {
            System.out.println("正在停止任务：" + id);
            CommandTasker tasker = taskDao.get(id);
            if (taskHandler.stop(tasker.getProcess(), tasker.getThread())) {
                taskDao.remove(id);
                System.out.println("停止任务成功！id=" + id);
                return true;
            }
        }
        System.err.println("停止任务失败！id=" + id);
        return false;
    }

    @Override
    public int stopAll() {
        Collection<CommandTasker> list = taskDao.getAll();
        Iterator<CommandTasker> iter = list.iterator();
        CommandTasker tasker = null;
        int index = 0;
        while (iter.hasNext()) {
            tasker = iter.next();
            if (taskHandler.stop(tasker.getProcess(), tasker.getThread())) {
                taskDao.remove(tasker.getId());
                index++;
            }
        }
        if (config.isDebug()) {
            System.out.println("停止了" + index + "个任务！");
        }
        return index;
    }

    private boolean checkConfig() {
//        config = new ProgramConfig();
        System.out.println(config);
        System.out.println(path);
        return config == null;
    }
}
